﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Distritos;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;
using Cesave.Domain.Core.Entities;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Modulos
{
	public partial class ModulosViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Distrito> _distritosModulo;

		/// <summary>
		/// 
		/// </summary>
		private Distrito _distritoModulo;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Distrito> DistritosModulo
		{
			get
			{
				return _distritosModulo;
			}
			private set
			{
				_distritosModulo = value;
				if (_distritosModulo != null)
					RaisePropertyChanged("DistritosModulo");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Distrito DistritoModulo
		{
			get
			{
				return _distritoModulo;
			}
			private set
			{
				_distritoModulo = value;
				if (_distritoModulo != null)
					RaisePropertyChanged("DistritoModulo");
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadDistritosModulo()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IDistritoService service = IoCFactory.Resolve<IDistritoService>();
					e.Result = service.FindDistritosByEstado(EstadoModulo.EstadoGuid);
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						DistritosModulo = e.Result as List<Distrito>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentDistritoModulo(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if ((bindingSource != null) && (bindingSource.Current != null))
				DistritoModulo = bindingSource.Current as Distrito;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnDistritosModuloPropertyChanged()
		{
			_view.distritosModuloBindingSource.DataSource = DistritosModulo;
			_view.distritosModuloBindingSource.CurrentChanged += SetCurrentDistritoModulo;
			SetCurrentDistritoModulo(_view.distritosModuloBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnDistritoModuloPropertyChanged()
		{
		}

		#endregion
	}
}